package com.itheima.gate.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/12/6 10:08
 */
@Component
public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        if(currentContext!=null){
            HttpServletRequest request = currentContext.getRequest();
            //登录请求放行
            if(request!=null && request.getRequestURI().indexOf("/sys/login")!=-1){
                return null;
            }
            //刷脸登录放行
            if(request!=null && request.getRequestURI().indexOf("/sys/faceLogin")!=-1){
                return null;
            }
            if(request!=null){
                //获取请求头
                String authorization = request.getHeader("Authorization");
                if(StringUtils.isBlank(authorization)){
                    currentContext.setSendZuulResponse(false);
                    currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
                }
            }
        }
        //校验通过
        return null;
    }
}
